package container

import (
	"myproject/pkg/aliyun"
	// "myproject/pkg/aliyun/ecs"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/cdn"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"

	"sync"
)

type ClientFactory[T any] func(*aliyun.BaseClient) T

type ClientContainer[T any] struct {
	client T
	once   sync.Once
}

type Container struct {
	baseClient *aliyun.BaseClient
	clients    map[string]*any
	mu         sync.RWMutex
}

func NewContainer(baseClient *aliyun.BaseClient) *Container {
	return &Container{
		baseClient: baseClient,
		clients:    make(map[string]*any),
	}
}

func (c *Container) GetClient(key string, factory ClientFactory[any]) any {
	c.mu.Lock()
	defer c.mu.Unlock()
	if client, ok := c.clients[key]; ok {
		return *client
	}

	newClient := factory(c.baseClient)
	c.clients[key] = &newClient
	return newClient
}
func (c *Container) GetCDNClient() *cdn.Client {
	// return c.GetClient("cdn", func(base *aliyun.BaseClient) any { return cdn.NewClient(base) }).(*cdn.Client)
	// return c.GetClient("cdn", func(base *aliyun.BaseClient) any { return cdn.NewClient(base) }).(*cdn.Client)
	return c.GetClient("cdn", func(base *aliyun.BaseClient) any {
		client, err := cdn.NewClientWithAccessKey(base.RegionId, base.AccessKeyId, base.AccessKeySecret)
		if err != nil {
			panic(err)
		}
		return client
	}).(*cdn.Client)

}

func (c *Container) GetECSClient() *ecs.Client {
	return c.GetClient("ecs", func(base *aliyun.BaseClient) any {
		client, err := ecs.NewClientWithAccessKey(base.RegionId, base.AccessKeyId, base.AccessKeySecret)
		if err != nil {
			panic(err)
		}
		return client
	}).(*ecs.Client)
}
